package com.zbkj.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.model.shop.EbIndustryCategory;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.EbIndustryCategoryRequest;
import com.zbkj.service.dao.shop.EbIndustryCategoryDao;
import com.zbkj.service.service.EbIndustryCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EbIndustryCategoryServiceImpl extends ServiceImpl<EbIndustryCategoryDao, EbIndustryCategory>
        implements EbIndustryCategoryService {

    @Autowired
    private EbIndustryCategoryDao ebIndustryCategoryDao;

    /**
     * 新增行业分类
     *
     * @param category 行业分类对象
     * @return 是否成功
     */
    @Override
    public EbIndustryCategory add(EbIndustryCategory category) {
        log.info("开始新增行业分类: {}", category);
        Date date = new Date();
        category.setCreateTime(date);
        category.setUpdateTime(date);
        ebIndustryCategoryDao.insert(category);
        return category;
    }

    /**
     * 更新行业分类
     *
     * @param category 行业分类对象
     * @return 是否成功
     */
    @Override
    public EbIndustryCategory update(EbIndustryCategory category) {
        log.info("开始更新行业分类: {}", category);
        Date date = new Date();
        category.setUpdateTime(date);
        ebIndustryCategoryDao.updateById(category);
        return category;
    }

    /**
     * 删除行业分类
     *
     * @param id 行业分类ID
     * @return 是否成功
     */
    @Override
    public boolean delete(Integer id) {
        log.info("开始删除行业分类, ID: {}", id);
        return ebIndustryCategoryDao.deleteById(id) > 0;
    }

    /**
     * 根据ID查询行业分类
     *
     * @param id 行业分类ID
     * @return 行业分类对象
     */
    @Override
    public EbIndustryCategory getById(Integer id) {
        log.info("开始查询行业分类, ID: {}", id);
        return ebIndustryCategoryDao.selectById(id);
    }

    /**
     * 分页查询
     *
     * @return
     */
    @Override
    public PageInfo<EbIndustryCategory> getPage(EbIndustryCategoryRequest request) {
        log.info("getPage: page={}, size={}", request.getPage(), request.getLimit());
        if (request.getPid() != null
                && request.getPid() == -2) {
            request.setPid(null);
        }

        Page<EbIndustryCategory> page = PageHelper.startPage(request.getPage(), request.getLimit());
        List<EbIndustryCategory> list = ebIndustryCategoryDao.selectList(
                new LambdaQueryWrapper<EbIndustryCategory>()
                        .eq(request.getPid() != null, EbIndustryCategory::getPid, request.getPid())
                        .like(StringUtils.isNotBlank(request.getName()), EbIndustryCategory::getName, request.getName())
        );
        list.add(0,new EbIndustryCategory()
                .setId(-3)
                .setName("全部")
                .setPid(request.getPid())
        );
        return CommonPage.copyPageInfo(page, list);
    }

    /**
     * 分页查询
     *
     * @return
     */
    @Override
    public List<EbIndustryCategory> findByList(EbIndustryCategoryRequest request) {
        if (request.getPid() != null && request.getPid() == -2) {
            request.setPid(null);
        }
        List<EbIndustryCategory> list = ebIndustryCategoryDao.selectList(
                new LambdaQueryWrapper<EbIndustryCategory>()
                        .eq(EbIndustryCategory::getPid, request.getPid())
        );

        return list;
    }

    @Override
    public List<String> getIndustryList(List<Integer> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return new ArrayList<>();
        }
        List<EbIndustryCategory> list = ebIndustryCategoryDao.selectList(
                new LambdaQueryWrapper<EbIndustryCategory>()
                        .in(EbIndustryCategory::getId, idList)
        );
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        return list.stream()
                .map(EbIndustryCategory::getName)
                .collect(Collectors.toList());
    }

    @Override
    public List<Map<String, Object>> getLabelList(EbIndustryCategoryRequest ebIndustryCategoryRequest) {
        // 查询所有行业分类数据
        List<EbIndustryCategory> list = ebIndustryCategoryDao.selectList(
                new LambdaQueryWrapper<EbIndustryCategory>()
        );

        // 构建三级分类树状结构
        List<Map<String, Object>> result = new ArrayList<>();

        // 筛选出一级分类（pid为0或null的分类）
        List<EbIndustryCategory> firstLevel = list.stream()
                .filter(category -> category.getPid() == null || category.getPid() == -1)
                .collect(Collectors.toList());

        // 构建树状结构
        for (EbIndustryCategory first : firstLevel) {
            Map<String, Object> firstMap = new HashMap<>();
            firstMap.put("id", first.getId());
            firstMap.put("parents", null);
            firstMap.put("name", first.getName());
            firstMap.put("icon", first.getIcon());
            firstMap.put("sort", first.getSort());
            // 查找二级分类
            List<Map<String, Object>> secondLevel = new ArrayList<>();
            List<EbIndustryCategory> secondCategories = list.stream()
                    .filter(category -> first.getId().equals(category.getPid()))
                    .collect(Collectors.toList());

            for (EbIndustryCategory second : secondCategories) {
                Map<String, Object> secondMap = new HashMap<>();
                secondMap.put("id", second.getId());
                secondMap.put("parents", second.getPid());
                secondMap.put("name", second.getName());
                secondMap.put("icon", second.getIcon());
                secondMap.put("sort", second.getSort());
                secondMap.put("status", second.getStatus());

                // 查找三级分类
                List<Map<String, Object>> thirdLevel = new ArrayList<>();
                List<EbIndustryCategory> thirdCategories = list.stream()
                        .filter(category -> second.getId().equals(category.getPid()))
                        .collect(Collectors.toList());

                for (EbIndustryCategory third : thirdCategories) {
                    Map<String, Object> thirdMap = new HashMap<>();
                    thirdMap.put("id", third.getId());
                    thirdMap.put("parents", third.getPid());
                    thirdMap.put("name", third.getName());
                    thirdMap.put("icon", third.getIcon());
                    thirdMap.put("sort", third.getSort());
                    thirdMap.put("status", third.getStatus());
                    thirdLevel.add(thirdMap);
                }

                secondMap.put("children", thirdLevel);
                secondLevel.add(secondMap);
            }

            firstMap.put("children", secondLevel);
            result.add(firstMap);
        }

        return result;
    }
}
